import { v4 as uuidv4 } from 'uuid';

export const getUUid = () => {
    return uuidv4().replace(/-/g, '');
}

/**
 * 根据匹配内容替换
 * 例子：dataSource = [{name:'张三',class:'1',age:18},{name:'李四',class:'2',age:19}],matchDataSource = [{name:'张三',class:'1',code:'2001'},{name:'张三',class:'2',code:'2002'}],
 * targetColumns = ['name','class'],matchColumns = ['name','class'],matchValue = 'code'
 * 最后结果为：[{name:'张三',class:'1',age:18,code:'2001'},{name:'李四',class:'2',age:19,code:'2002'}]
 */
export const matchDataReplace = (dataSource: any[], matchDataSource: any[], targetColumns: any[], matchColumns: any[], matchValue: string) => {
    return dataSource.map(item => {
        const newItem = {...item};
        const matched = matchDataSource.find(matchItem => {
            return matchColumns.every(column => {
                return item[column] === matchItem[column];
            });
        });
        if (matched) {
            newItem[matchValue] = matched[matchValue];
        }
        return newItem;
    });
}

export function combineInsertStatementsFromText(inputText) {
    // 正则表达式匹配带列名的 INSERT 语句
    const regexWithColumns = /insert\s+into\s+(\S+)\s*\((.+)\)\s*values\s*\((.+)\);/i
    // 正则表达式匹配不带列名的 INSERT 语句
    const regexWithoutColumns = /insert\s+into\s+(\S+)\s*values\s*\((.+)\);/i

    let tableName = ''
    let columns = ''
    let valuesList = []
    let foundColumns = false // 是否找到了列名

    // 将输入文本按照每一行拆分
    const statements = inputText.split('\n').filter((line) => line.trim() !== '')

    statements.forEach((statement) => {
        // 优先匹配带列名的语句
        let match = statement.match(regexWithColumns)
        if (match) {
            if (!tableName) {
                tableName = match[1] // 表名
                columns = match[2] // 列名
                foundColumns = true
            }
            valuesList.push(`  (${match[3]})`) // 取出每个值，并加上缩进
        } else {
            // 尝试匹配不带列名的语句
            match = statement.match(regexWithoutColumns)
            if (match) {
                if (!tableName) {
                    tableName = match[1] // 表名
                }
                valuesList.push(`  (${match[2]})`) // 取出每个值，并加上缩进
            }
        }
    })

    // 合并成一个插入语句
    if (valuesList.length > 0) {
        // 如果找到了列名，拼接列名，否则省略列名
        const columnsPart = foundColumns ? `(${columns})` : ''
        const combinedInsertStatement = `INSERT INTO ${tableName} ${columnsPart}\nVALUES\n${valuesList.join(',\n')};`
        return combinedInsertStatement
    } else {
        return '未找到有效的 INSERT 语句。'
    }
}